package com.tarena.dang.services.impl;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import com.tarena.dang.daos.ProductDAO;
import com.tarena.dang.daos.impl.JdbcProductDAO;
import com.tarena.dang.pojos.Book;
import com.tarena.dang.pojos.Category;
import com.tarena.dang.pojos.Product;
import com.tarena.dang.services.ProductService;

public class ProductServiceImpl implements ProductService {
	private static ProductDAO productDAO = new JdbcProductDAO();

	// private static List<Category> list;

	public List<Product> findNewProduct(int topSize) throws Exception {

		return productDAO.findNewProduct(topSize);
	}

	public List<Book> findBookByCatId(int currentId, int page, int pageSize)
			throws Exception {

		return productDAO.findBookListByCatId(currentId, page, pageSize);
	}

	// public int loadMaxPage(int totalBook, int pageSize) {
	// return totalBook % pageSize == 0 ? totalBook / pageSize : totalBook
	// / pageSize + 1;
	// }

	public int loadMaxPage(List<Category> categorys, int currentId, int pageSize) {
		int totalBook = 0;
		for (Category c : categorys) {
			if (c.getId() == currentId) {
				totalBook = c.getPnum();
			}
		}
		return totalBook % pageSize == 0 ? totalBook / pageSize : totalBook
				/ pageSize + 1;
	}

	public List<Category> findBookCatsById(int pid) throws Exception {
		List<Category> list = productDAO.findBookById(pid);
		Collections.sort(list, new Comparator<Category>() {

			public int compare(Category c1, Category c2) {
				return c1.getId() - c2.getId();
			}

		});
		return list;
	}

	public Book findBook(List<Category> list) throws Exception {
		Book book = null;
		for (Category c : list) {
			if (c.getBook() != null) {
				book = c.getBook();
			}
		}
		return book;
	}

}
